package com.changgou.system.filter;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.InetSocketAddress;

@Component //将过滤器 添加到Spring容器中 , 如果不添加则不生效
public class IpFilter implements GlobalFilter, Ordered {

    //过滤的 逻辑业务代码 需求 : 如果访问IP为 : 22.22.22.22则拦截 返回一个405错误,反之 放行
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        InetSocketAddress remoteAddress = request.getRemoteAddress();
        System.out.println("拦截到的IP地址为: " + remoteAddress);
        if(remoteAddress.equals("22.22.22.22")){
            //拦截到IP地址为 22.22.22.22 ,返回405错误
            ServerHttpResponse response = exchange.getResponse(); //获取response

            response.setStatusCode(HttpStatus.FORBIDDEN); //设置返回的错误码
            System.out.println("该IP已被服务器加入黑名单: " +remoteAddress);
            return response.setComplete(); //返回 错误码 ,并拦截该请求不放行
        }

        //放行;
        return chain.filter(exchange);
    }

    //返回值, 决定着 该过滤器的优先级,越低优先级越高
    @Override
    public int getOrder() {
        return 1;
    }
}
